package com.thoughtworks.impersonator.http.message.storage;

import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;

import com.thoughtworks.impersonator.http.message.RawRequest;
import com.thoughtworks.impersonator.http.message.RawResponse;
import com.thoughtworks.impersonator.http.message.RequestIdentifier;
import com.thoughtworks.impersonator.http.message.transform.RequestTransformer;
import com.thoughtworks.impersonator.http.message.transform.ResponseTransformer;

public class HttpExchangeSerialiser {
    private final RequestIdentifier requestIdentifier;
    private final RequestTransformer requestTransformer;
    private final ResponseTransformer responseTransformer;

    public HttpExchangeSerialiser(RequestIdentifier requestIdentifier, RequestTransformer requestTransformer,
            ResponseTransformer responseTransformer) {
                this.requestIdentifier = requestIdentifier;
                this.requestTransformer = requestTransformer;
                this.responseTransformer = responseTransformer;
    }

    public String identify(HttpRequest request) {
        RawRequest rawRequest = new RawRequest(request);
        return requestIdentifier.calculateUid(rawRequest);
    }

    public HttpResponse deserialiseResponse(String contents) {
        RawResponse rawResponse = new RawResponse(contents);
        responseTransformer.transform(rawResponse);
        return rawResponse.toHttpResponse();
    }

    public String serialise(HttpRequest request) {
        RawRequest rawRequest = new RawRequest(request);
        requestTransformer.transform(rawRequest);
        return rawRequest.toString();
    }

    public HttpRequest deserialiseRequest(String contents) {
        RawRequest rawRequest = new RawRequest(contents);
        requestTransformer.transform(rawRequest);
        return rawRequest.toHttpRequest();
    }

    public String serialise(HttpResponse response) {
        RawResponse rawResponse = new RawResponse(response);
        responseTransformer.transform(rawResponse);
        return rawResponse.toString();
    }

}
